package tool.ducong.com.mygpsdemo;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.widget.Switch;
import android.widget.TextView;

import android.provider.Settings;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import mytool.Distance;
import mytool.Gps2BaiDu;
import mytool.Itude;
import mytool.ListTools;
import mytool.PrintLog;
import mytool.ToastShow;

/**
 * Created by zerdoor_pc on 2016/1/28.
 */
public class GPS_TOOL {
    private Activity context;
    private int id;
    private String TAG = "GPS";

    public GPS_TOOL(Activity context, int id) {
        this.context = context;
        this.id = id;
    }

    public Boolean openGPSSettings() {
        LocationManager alm = (LocationManager) context
                .getSystemService(Context.LOCATION_SERVICE);
        if (alm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
            try {

                ToastShow.showShort(context, "GPS模块正常");
            } catch (Exception e) {
            }
            PrintLog.i("MYGPSDEMO=GPS模块正常");
            getLocation();
            return true;
        }
        try {
            PrintLog.i("MYGPSDEMO=请开启GPS");
            ToastShow.showShort(context, "请开启GPS");
        } catch (Exception e) {
        }
        Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
        context.startActivityForResult(intent, 0); //此为设置完成后返回到获取界面
        return false;

    }

    public Boolean checkGPS() {
        LocationManager alm = (LocationManager) context
                .getSystemService(Context.LOCATION_SERVICE);
        if (alm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
            ToastShow.showShort(context, "GPS模块正常");
            getLocation();
            PrintLog.i("MYGPSDEMO=GPS模块正常2");

            return true;
        }
        ToastShow.showShort(context, "请开启GPS");
        PrintLog.i("MYGPSDEMO=请开启GPS2");
        return false;
    }

    LocationManager locationManager;

    public void getLocation() {
        // 获取位置管理服务

        String serviceName = Context.LOCATION_SERVICE;

        locationManager = (LocationManager) context.getSystemService(serviceName);
        // 查找到服务信息
        String provider = locationManager.getBestProvider(getCriteria(), true); // 获取GPS信息
        Location location = locationManager.getLastKnownLocation(provider);

        updateToNewLocation(location);
        //监听状态
        locationManager.addGpsStatusListener(listener);
        // 设置监听器，自动更新的最小时间为间隔N秒(1秒为1*1000，这样写主要为了方便)或最小位移变化超过N米
        locationManager.requestLocationUpdates(provider, MyAPP.time * 1000, 0,
                locationListener);
    }

    public void setTimes() {
        String provider = locationManager.getBestProvider(getCriteria(), true); // 获取GPS信息
        locationManager.requestLocationUpdates(provider, MyAPP.time * 1000, 0,
                locationListener);
    }


    public void onActivityDestroy() {
        locationManager.clearTestProviderEnabled(locationManager.getBestProvider(getCriteria(), true));
        locationManager.removeGpsStatusListener(listener);
        locationManager.removeUpdates(locationListener);
    }

    /**
     * 返回查询条件
     *
     * @return
     */
    public Criteria getCriteria() {
        Criteria criteria = new Criteria();
        //设置定位精确度 Criteria.ACCURACY_COARSE比较粗略，Criteria.ACCURACY_FINE则比较精细
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        //设置是否要求速度
        criteria.setSpeedRequired(false);
        // 设置是否允许运营商收费
        criteria.setCostAllowed(false);
        //设置是否需要方位信息
        criteria.setBearingRequired(false);
        //设置是否需要海拔信息
        criteria.setAltitudeRequired(false);
        // 设置对电源的需求
//        criteria.setPowerRequirement(Criteria.POWER_MEDIUM);
        criteria.setPowerRequirement(MyAPP.POWER);

        return criteria;
    }

    List<Itude> myItude = new ArrayList<>();
    List<Double> myAccuracy = new ArrayList<>();
    private Boolean ismoving=false;
    private int  times=0;
    public void updateToNewLocation(Location location) {

        TextView tv1;
        tv1 = (TextView) context.findViewById(id);
        if (location != null) {
            double latitude = location.getLatitude();
            double longitude = location.getLongitude();
            Itude itude = new Itude();
            itude.setLatitude(latitude);
            itude.setLongitude(longitude);
            //MyAPP.ACCURACY;
            // Distance.getDisance(lat, lon , 30.570495625, 104.05860551388889))

            if (myItude.size() < MyAPP.Minimum) {
                myItude.add(itude);
                tv1.setText("");
                sendUpdate(itude, tv1);
            } else {
                Itude average = ListTools.getItude(myItude);
                double s = Distance.getDisance(itude.getLatitude(), itude.getLongitude(), average.getLatitude(), average.getLongitude());
                tv1.append("\nGps距离判断s=" + s);
                if (s <= MyAPP.ACCURACY+1) {
                    myAccuracy.add(s);
                    if (myAccuracy.size() >= MyAPP.Minimum) {

                        //MyAPP.ACCURACY = ListTools.getItude_Double(myAccuracy);
                        if (MyAPP.ACCURACY<=MyAPP.MinACCURACY)MyAPP.ACCURACY=MyAPP.MinACCURACY;
                        ListTools.check(myAccuracy, MyAPP.Maximum, 0);
                    }
                    if (MyAPP.ACCURACY>50&&MyAPP.ACCURACY>ListTools.getItude_Double(myAccuracy)){
                        MyAPP.ACCURACY -=5;
                    }else{
                        if (MyAPP.ACCURACY>ListTools.getItude_Double(myAccuracy)){
                            MyAPP.ACCURACY -=1;
                        }else{
                            MyAPP.ACCURACY +=5;
                        }
                    }
                    tv1.setText("Gps定位点精度s=" + s+"\n过滤精度："+MyAPP.ACCURACY);
                    myItude.add(itude);
                    sendUpdate(itude, tv1);
                    ListTools.check(myItude, MyAPP.Maximum/2);
                }else{
                    times++;
                    if (times>=MyAPP.Maximum/2){
                        MyAPP.ACCURACY=MyAPP.OldACCURACY;
                        times=0;
                        myItude.clear();
                        myAccuracy.clear();
                    }
                }

            }
            // PrintLog.i("HTTPURL:发送更新");
//            if (MyAPP.olditude!=null&&MyAPP.itude.getLatitude()==MyAPP.olditude.getLatitude()&&MyAPP.itude.getLongitude()==MyAPP.olditude.getLongitude()){
//                return;
//            }
            // PrintLog.i("HTTPURL:url=时间：" + location.getTime());
            // PrintLog.i("HTTPURL:url=经度：" + location.getLongitude());
            // PrintLog.i("HTTPURL:url=纬度：" + location.getLatitude());
            // PrintLog.i("HTTPURL:url=海拔：" + location.getAltitude());
//            MyAPP.olditude=MyAPP.itude;

        } else {
//            openGPSSettings();
            tv1.setText("无法获取地理信息");
            PrintLog.i("无法获取地理信息");
            MyAPP.itude = null;
//            MyAPP.olditude=null;
        }

    }

    private void sendUpdate(Itude itude, TextView tv1) {
        MyAPP.itude = itude;
        MyAPP.handler.sendEmptyMessage(0);
        tv1.append("\n维度：" + itude.getLatitude() + "\n经度" + itude.getLongitude());
        PrintLog.i("HTTPURL:返回数据:" + myItude.size());
    }

    private LocationListener locationListener = new LocationListener() {

        /**
         * 位置信息变化时触发
         */
        public void onLocationChanged(Location location) {

            PrintLog.i("HTTPURL：当前GPS位置变化");
            updateToNewLocation(location);

        }

        /**
         * GPS状态变化时触发
         */
        public void onStatusChanged(String provider, int status, Bundle extras) {
            switch (status) {
                //GPS状态为可见时
                case LocationProvider.AVAILABLE:
                    PrintLog.i(TAG + "当前GPS状态为可见状态");
                    break;
                //GPS状态为服务区外时
                case LocationProvider.OUT_OF_SERVICE:
                    PrintLog.i(TAG + "当前GPS状态为服务区外状态");
                    break;
                //GPS状态为暂停服务时
                case LocationProvider.TEMPORARILY_UNAVAILABLE:
                    PrintLog.i(TAG + "当前GPS状态为暂停服务状态");
                    break;
            }
        }

        /**
         * GPS开启时触发
         */
        public void onProviderEnabled(String provider) {
            Location location = locationManager.getLastKnownLocation(provider);
            updateToNewLocation(location);
        }

        /**
         * GPS禁用时触发
         */
        public void onProviderDisabled(String provider) {
            updateToNewLocation(null);
        }


    };


    //状态监听
    GpsStatus.Listener listener = new GpsStatus.Listener() {
        public void onGpsStatusChanged(int event) {
            switch (event) {
                //第一次定位
                case GpsStatus.GPS_EVENT_FIRST_FIX:
                    PrintLog.i(TAG + "第一次定位");
                    break;
                //卫星状态改变
                case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
                    PrintLog.i(TAG + "卫星状态改变");

                    //获取当前状态
                    GpsStatus gpsStatus = locationManager.getGpsStatus(null);
                    //获取卫星颗数的默认最大值
                    int maxSatellites = gpsStatus.getMaxSatellites();
                    //创建一个迭代器保存所有卫星
                    Iterator<GpsSatellite> iters = gpsStatus.getSatellites().iterator();
                    int count = 0;
                    while (iters.hasNext() && count <= maxSatellites) {
                        GpsSatellite s = iters.next();
                        count++;
                    }

                    if (oldcount != count) {
                        ToastShow.showShort(context, "搜索到：" + count + "颗卫星");
                        oldcount = count;
                    }
//                    System.out.println("搜索到："+count+"颗卫星");
                    break;
                //定位启动
                case GpsStatus.GPS_EVENT_STARTED:
                    PrintLog.i(TAG + "定位启动");
                    break;
                //定位结束
                case GpsStatus.GPS_EVENT_STOPPED:
                    PrintLog.i(TAG + "定位结束");
                    break;
            }
        }

        ;
    };
    int oldcount = 0;
}
